module utils.my_jwt;

import vibe.http.server : HTTPServerRequest, HTTPServerResponse;
import vibe.data.json : Json, parseJsonString;
import fastjwt.jwt;
import stringbuffer;
import utils.const_val;

/** 
 * 生成token
 * Params:
 *   userData = 用户信息
 */
string createToken (Json userData)
{
    import std.format : format;

    StringBuffer buf;
    encodeJWTToken(buf, JWTAlgorithm.HS256, JWT_SECRET_STR, userData);

    string token = format("%s", buf.getData!string());
    return token;
}

/** 
 * 验证token
 */
void jwtValidator (HTTPServerRequest req, HTTPServerResponse resp)
{
    import std.algorithm.searching : startsWith;
    import std.datetime.systime : Clock;

    string authStr = "Authorization";
    string bearer = "Bearer ";

    Json data = Json.emptyObject;
    data["code"] = 401;
    data["msg"] = "未授权";
    data["data"] = null;

    if (authStr !in req.headers || !req.headers[authStr].startsWith(bearer))
    {
        data["msg"] = "请登录";
        return resp.writeJsonBody(data, 401);
    }

    StringBuffer header;
    StringBuffer payload;

    const result = decodeJWTToken(req.headers[authStr][bearer.length .. $],
        JWT_SECRET_STR, JWTAlgorithm.HS256, header, payload);
    if (result > 0)
    {
        data["msg"] = "token不正确";
        return resp.writeJsonBody(data, 401);
    }

    Json pdata = parseJsonString(payload.getData());
    if (pdata["exp"].type == Json.Type.undefined)
    {
        data["msg"] = "token不正确";
        return resp.writeJsonBody(data, 401);
    }

    long exp = pdata["exp"].to!long();
    long now = Clock.currTime.toUnixTime();
    if (exp <= now)
    {
        data["msg"] = "token已过期";
        return resp.writeJsonBody(data, 401);
    }
}
